<template>
  <picker :ref="id"  :visible="value" :row-number="7" :default-index="defaultIndex" @cancel="cancel" @confirm="confirm" :data="pickerData" :showToolbar="true" ></picker>
</template>
<script>
  import picker from "ssit-mobile-picker"
  export default {
    props: {
      value:{
        type:Boolean,
        default:false
      },
      num:{
        type:Number,
        default:2
      },
      init:{
        type:Array,
        default:[]
      }
    },
    components:{
      picker
    },
    computed:{
      initStr(){
        return this.init.join(",")
      }
    },
    created(){
      this.pickerData.push(this.getYearList())
      this.pickerData.push(this.getMonthList())
      if(this.num>1){
        this.pickerData.push(this.getYearList())
        this.pickerData.push(this.getMonthList())
      }
      this.setDefaultIndexData();
    },
    data () {
      return {
        id:"picker"+Math.floor(Math.random()*10000),
        pickerData:[],
        defaultIndex:[]
      }
    },
    methods:{
      getYearList(){
        let nowYear  = new Date().getFullYear();
        let start = 2010;
        let yearList = [];
        for(let i=0;i<=nowYear-start;i++){
          yearList.push({label:start+i+"年",value:start+i});
        }
        return yearList;
      },
      getMonthList(){
        let monthList = [];
        for (let i = 1; i <=12 ; i++) {
          let month = i<10?"0"+i:i+"";
          monthList.push({label:month+"月",value:month})
        }
        return monthList;
      },
      cancel(){
        this.$emit("input",false);
      },
      confirm(val){
        let result = []
        result.push(val[0].value+"-"+val[1].value);
        if(this.num>1){
          result.push(val[2].value+"-"+val[3].value);
        }
        this.$emit("confirm",result);
        this.cancel();
      },
      setDefaultIndexData(){
        let defaultIndex = [];
        if(this.init.length>0){
          let startTime = this.init[0];
          if(startTime.indexOf("-")>0){
            defaultIndex.push(this.pickerData[0].findIndex(item=>{return item.value==startTime.split("-")[0]}))
            defaultIndex.push(this.pickerData[1].findIndex(item=>{return item.value==startTime.split("-")[1]}))
          }else{
            defaultIndex.push(0);
            defaultIndex.push(0);
          }
        }
        if(this.init.length>1){
          let endTime = this.init[1];
          if(endTime.indexOf("-")>0){
            defaultIndex.push(this.pickerData[2].findIndex(item=>{return item.value==endTime.split("-")[0]}))
            defaultIndex.push(this.pickerData[3].findIndex(item=>{return item.value==endTime.split("-")[1]}))
          }else{
            defaultIndex.push(0);
            defaultIndex.push(0);
          }
        }
        this.defaultIndex = defaultIndex;
      },
    },
    watch:{
      initStr(old,newData){
        this.setDefaultIndexData();
      }
    }
  }
</script>
